package ws.cmpe451.group7.ourcity.webservice.recommendation;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cmpe451.group7.ourcity.entity.Tag;
import cmpe451.group7.ourcity.recommendation.FreebaseQuery;
import cmpe451.group7.ourcity.util.JSONUtils;

/**
 * Controller for handling auto complete tags
 */
@Controller
public class AutocompleteController {

	/**
	 * Complete the city with the given parameters
	 * 
	 * @param request
	 * @param response
	 * @param country
	 *            can be empty
	 * @param city
	 *            first few characters of the city
	 * @throws IOException
	 * @throws JSONException
	 */
	@Transactional
	@RequestMapping("/webservice/recommendation/completeCity")
	public void completeCity(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("country") String country,
			@RequestParam("city") String city) throws IOException,
			JSONException {

		PrintWriter responseWriter = response.getWriter();

		if (StringUtils.isEmpty(city)) {
			responseWriter.print("{\"success\":0, \"error\":\"Empty city\"}");
			return;
		}

		List<String> completeCity = null;
		if (StringUtils.isNotEmpty(country)) {
			completeCity = FreebaseQuery.completeCity(country, city);
		} else {
			completeCity = FreebaseQuery.completeCity(city);
		}

		if (CollectionUtils.isEmpty(completeCity)) {
			responseWriter.print("{\"success\":0, \"data\": []");
		}

		JSONUtils.JSONListWriter(completeCity, responseWriter);
	}

	/**
	 * Complete a tag by using the Freebase service
	 * 
	 * @param request
	 * @param response
	 * @param tag
	 *            first few characters of the name of the tag
	 * @throws IOException
	 * @throws JSONException
	 */
	@Transactional
	@RequestMapping("/webservice/recommendation/completeTag")
	public void completeTag(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("tag") String tag)
			throws IOException, JSONException {

		PrintWriter responseWriter = response.getWriter();

		if (StringUtils.isEmpty(tag)) {
			responseWriter.print("{\"success\":0, \"error\":\"Empty tag\"}");
			return;
		}

		List<Tag> completeTags = FreebaseQuery.completeTags(tag);

		JSONUtils.JSONListWriter(completeTags, responseWriter);
	}

}
